#![allow(dead_code)]
use super::{ThreadPool,ThreadTask};
use std::sync::Arc;

#[async_trait::async_trait]
pub trait AsyncThreadTask{
    async fn call(&self,_: ThreadPool);
}

#[derive(Clone)]
pub struct  AsyncTask<T:AsyncThreadTask + 'static>{
    task:Arc<T>
}
impl<T> AsyncTask<T>
    where T: AsyncThreadTask + 'static
{
    pub fn new(t:T)->Self
    {
        let task = Arc::new(t);
        Self{task}
    }
    //异步调用
    pub fn call(&self,tp:ThreadPool){
        let task = self.task.clone();
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build().expect("线程异步运行时构建错误")
            // .spawn_blocking();
            .block_on(async move{
                task.call(tp).await;
            });
    }
}

#[macro_export]
macro_rules! thread_async_handle {
    ($func:stmt)=>{
        let local = tokio::task::LocalSet::new();
        local.spawn_local(async move{
                $func
            });
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build().expect("线程异步运行时构建错误")
            .block_on(local);
    }
}

impl<T:AsyncThreadTask + 'static> ThreadTask for AsyncTask<T>
{
    fn call(&self, tp: &ThreadPool) {
        self.call(tp.clone());
    }
}
